<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="姓名">
                <a-input v-model="queryParam.userName" placeholder="" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="手机号码">
                <a-input v-model="queryParam.mobile" placeholder="" />
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="申请状态">
                  <a-select v-model="queryParam.creditLevel" placeholder="请选择">
                    <a-select-option value="0">未审核</a-select-option>
                    <a-select-option value="1">审核通过</a-select-option>
                    <a-select-option value="2">审核未通过</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="申请开始时间">
                  <a-date-picker v-model="queryParam.startCreateTime" style="width: 100%" placeholder="申请开始时间" />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="申请结束时间">
                  <a-date-picker v-model="queryParam.endCreateTime" style="width: 100%" placeholder="申请结束时间" />
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="8" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (this.queryParam = {})">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="applyId"
        :columns="columns"
        :data="loadData"
        :alert="false"
        showPagination="auto"
        listName="applyList"
        :scroll="{ x: 'calc(500px + 100%)' }"
        v-if="btnsPurviewData.query.isShow"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="status" slot-scope="text">
          {{ text | statusFilter }}
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <span v-if="btnsPurviewData.audit.isShow">
              <a @click="_rejectApply(record)" v-if="record.status === 0">驳回</a>
              <span class="disabled" v-else>驳回</span>
              <a-divider type="vertical" />
              <a @click="_agreeApply(record)" v-if="record.status === 0">关联商户</a>
              <span class="disabled" v-else>关联商户</span>
              <a-divider type="vertical" />
            </span>
            <span v-if="btnsPurviewData.add.isShow">
              <a @click="_createMerchant(record)" v-if="record.status === 0">创建商户</a>
              <span class="disabled" v-else>创建商户</span>
            </span>
          </template>
        </span>
      </s-table>
      <create-audit-form
        ref="createRejectForm"
        :visible="auditVisible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleAuditCancel"
        @ok="handleAuditOk"
      >
      </create-audit-form>
      <create-form
        ref="createForm"
        :visible="visible"
        :loading="confirmLoading"
        :title="formTitle"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      >
      </create-form>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { BTNS_PURVIEW_MAP } from '@/store/mutation-types'
import storage from 'store'
import { STable, Ellipsis } from '@/components'
import { getMerchantApplyList, addMerchant, editMerchantStatus, merchantAudit } from '@/api/merchantManage'
import { getRepaymentPlanSelList } from '@/api/common'
import CreateAuditForm from './modules/CreateAuditForm'
import CreateForm from './modules/CreateMerchantForm'
const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' },
    align: 'center',
    fixed: 'left',
    width: 80
  },
  {
    title: '个人或公司名称',
    dataIndex: 'merchantName',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '姓名',
    dataIndex: 'contactName',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '手机号码',
    dataIndex: 'contactMobile',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '申请状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' },
    align: 'center'
  },
  {
    title: '审核原因',
    dataIndex: 'auditReason',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '审核人',
    dataIndex: 'auditUserName',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '240px',
    scopedSlots: { customRender: 'action' },
    align: 'center',
    fixed: 'right'
  }
]

const statusMap = {
  0: {
    text: '未审核'
  },
  1: {
    text: '审核通过'
  },
  2: {
    text: '审核未通过'
  }
}

export default {
  name: 'MerchantBusinessApplyList',
  components: {
    STable,
    Ellipsis,
    CreateAuditForm,
    CreateForm
  },
  data () {
    this.columns = columns
    return {
      btnsPurviewMap: storage.get(BTNS_PURVIEW_MAP),
      btnsPurviewData: {},
      // create model
      visible: false,
      auditVisible: false,
      confirmLoading: false,
      mdl: null,
      formTitle: '创建商户',
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getMerchantApplyList(requestParameters)
          .then((res) => {
            return res.result
          })
          .catch((e) => {})
      },
      selectedRowKeys: [],
      selectedRows: [],
      repaymentPlanSelList: []
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    }
  },
  created () {
    getRepaymentPlanSelList({})
      .then((res) => {
        this.repaymentPlanSelList = res.dataList
      })
      .catch((e) => {})
    this.btnsPurviewData = this.btnsPurviewMap[this.$route.meta.permission[0]]
  },
  computed: {},
  methods: {
    /**
     * 创建商户
     */
    _createMerchant (record) {
      this.visible = true
      this.mdl = { ...record }
    },
    /**
     * 驳回
     */
    _rejectApply (record) {
      this.auditVisible = true
      this.mdl = { ...record, auditType: 'isReject' }
    },
    /**
     * 同意
     */
    _agreeApply (record) {
      this.auditVisible = true
      this.mdl = { ...record, auditType: 'isAgree' }
    },

    /**
     * 切换searchBar展开/关闭
     */
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    /**
     * 切换商户状态
     */
    handleChangeStatus (record) {
      const params = { status: record.status === 1 ? 2 : 1, merchantList: [{ merchantId: record.merchantId }] }
      editMerchantStatus(params)
        .then((res) => {
          this.$refs.table.refresh()
          this.$message.info(`${record.status === 1 ? '冻结' : '启用'}成功`)
        })
        .catch((e) => {})
    },
    /**
     *  新建/修改商户
     */
    handleOk () {
      const form = this.$refs.createForm.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          // 修改 e.g.
          addMerchant(values)
            .then((res) => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.info('创建成功')
            })
            .catch((e) => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    /**
     * 取消表单
     */
    handleCancel () {
      this.visible = false
      this.confirmLoading = false
      const form = this.$refs.createForm.form
      form.resetFields() // 清理表单数据（可不做）
    },
    /**
     *  提交审核
     */
    handleAuditOk () {
      const form = this.$refs.createRejectForm.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (values.applyId) {
            // 修改 e.g.
            merchantAudit({ ...values, status: this.mdl === 'isReject' ? 2 : 1 })
              .then((res) => {
                this.auditVisible = false
                this.confirmLoading = false
                // 重置表单数据
                form.resetFields()
                // 刷新表格
                this.$refs.table.refresh()
                this.$message.info(this.mdl === 'isReject' ? '已驳回审核' : '已通过审核')
              })
              .catch((e) => {
                this.confirmLoading = false
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    /**
     * 取消表单
     */
    handleAuditCancel () {
      this.auditVisible = false
      this.confirmLoading = false
      const form = this.$refs.createRejectForm.form
      form.resetFields() // 清理表单数据（可不做）
    }
  }
}
</script>
<style lang="less" scope>
.disabled {
  cursor: not-allowed;
}
</style>
